from django import forms
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.db.models import Q
from django.urls import reverse
from django.views.generic import ListView
from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.contrib import messages
from .models import Student, PastExamScore, TargetScore
from .forms import StudentForm, PastExamScoreForm, StudyGoalForm, TargetScoreForm
from django.core.exceptions import ValidationError
from django.db import models
from django.core.paginator import Paginator
from django.db.models import Avg, Max
from django.utils import timezone



def user_login(request):
    """用户登录视图"""
    # 已登录用户直接跳转到学生列表页
    if request.user.is_authenticated:
        return redirect('users:student_list')

    if request.method == 'POST':
        # 获取表单提交的用户名和密码
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()

        # 验证用户名和密码（Django 内置认证）
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # 登录成功：记录用户会话
            login(request, user)
            messages.success(request, f'欢迎回来，{user.username}！')

            # 若有跳转前的目标页面（next参数），则跳转到该页面
            next_url = request.GET.get('next', '')
            if next_url:
                return redirect(next_url)
            # 无目标页面则默认跳转到学生列表
            return redirect('users:student_list')
        else:
            # 登录失败：提示错误
            messages.error(request, '用户名或密码错误，请重新输入！')

    # GET 请求：渲染登录表单
    return render(request, 'users/login.html', {'title': '用户登录'})

@login_required  # 仅允许已登录用户访问登出功能
def user_logout(request):
    """用户登出视图"""
    logout(request)
    messages.info(request, '已成功退出登录！')
    return redirect('users:user_login')  # 登出后跳回登录页

# 学生列表视图（类视图）：仅管理员可查看，支持分页
@method_decorator(login_required, name='dispatch')  # 基础登录保护：未登录不能进
class StudentListView(ListView):
    model = Student  # 关联的模型：Student（展示学生数据）
    template_name = 'users/student_list.html'  # 渲染的模板文件
    context_object_name = 'students'  # 模板中用「students」变量接收列表数据
    paginate_by = 10  # 分页：每页显示10条学生记录（避免数据多的时候页面卡顿）

    def dispatch(self, request, *args, **kwargs):
        """
        重写 dispatch 方法：新增管理员权限校验
        作用：普通学生登录后，即使知道列表页URL，也进不来
        """
        # 1. 先判断是否已登录（@method_decorator 已经做了，但这里再保险一次）
        if not request.user.is_authenticated:
            return redirect('users:login')  # 未登录 → 跳登录页

        # 2. 关键：判断是否是管理员（只有 is_superuser=True 才能看列表）
        if not request.user.is_superuser:
            messages.error(request, "您没有权限查看学生列表（仅管理员可操作）")
            # 普通学生 → 跳自己的个人信息页（而不是列表页）
            return redirect('users:student_detail', pk=request.user.student.id)

        # 3. 是管理员 → 正常进入列表页
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        重写 get_context_data：给模板传递额外数据（比如页面标题、添加学生的URL）
        模板中可以用这些变量做页面渲染
        """
        context = super().get_context_data(**kwargs)
        # 给模板传页面标题（比如列表页顶部显示“学生管理列表”）
        context['page_title'] = '学生管理列表'
        # 给模板传“添加学生”的URL（列表页的“添加学生”按钮会用到）
        context['add_student_url'] = 'users:student_create'
        context['search_query'] = self.request.GET.get('q', '').strip()
        return context

    def get_queryset(self):
        """
        重写 get_queryset：自定义列表数据的查询逻辑（可选，按需调整）
        比如：按“创建时间倒序”显示（最新添加的学生在前面），或按“目标院校”筛选
        """
        # 原逻辑：查询所有学生（Student.objects.all()）
        # 优化：按创建时间倒序（-created_at 表示“倒序”，created_at 是你Model中新增的字段）
        queryset = super().get_queryset().order_by('-created_at')

        # （可选）添加搜索功能：如果前端传了“搜索关键词”，按姓名/目标院校筛选
        search_keyword = self.request.GET.get('q', '').strip()
        if search_keyword:
            queryset = queryset.filter(
                Q(name__icontains=search_keyword) |
                Q(undergraduate_school__icontains=search_keyword) |
                Q(target_school__icontains=search_keyword) |
                Q(target_major__icontains=search_keyword)
            )
        return queryset


@login_required
def student_create(request):
    if not request.user.is_superuser:
        messages.error(request, "您没有权限添加学生（仅管理员可操作）")
        return redirect('users:student_list')

    if request.method == 'POST':
        form = StudentForm(request.POST, request=request)
        if form.is_valid():
            try:
                student = form.save(commit=True)

                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    username = form.cleaned_data.get('student_username')
                    password = form.cleaned_data.get('student_password')
                    return JsonResponse({
                        'success': True,
                        'message': f'学生信息添加成功！登录账号：{username}，初始密码：{password}',
                        'student_id': str(student.id),
                        'redirect_url': '/users/'
                    })

                messages.success(request, f'学生「{student.name}」信息添加成功！')
                return redirect('users:student_list')

            except ValueError as e:
                error_msg = f"数据错误：{str(e)}"
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return redirect('users:student_list')

            except ValidationError as e:
                error_msg = str(e)
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return render(request, 'users/student_form.html', {'form': form, 'title': '添加学生'})
            except Exception as e:
                error_msg = f'添加失败：{str(e)}'
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return render(request, 'users/student_form.html', {'form': form, 'title': '添加学生'})

        else:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'errors': form.errors})
            return render(request, 'users/student_form.html', {'form': form, 'title': '添加学生'})

    # GET请求
    else:
        try:
            form = StudentForm(request=request)
        except Exception as e:
            messages.error(request, f"创建表单时发生错误：{str(e)}")
            return redirect('users:student_list')

    return render(request, 'users/student_form.html', {'form': form, 'title': '添加学生'})


@login_required()
def student_detail(request, pk):
    """
    学生详情页视图。
    预处理所有数据计算，然后传递给模板进行渲染。
    """
    student = get_object_or_404(Student, pk=pk)

    # 1. 获取关联数据并排序
    past_scores = student.past_scores.all().order_by('-exam_year')
    study_goals = student.goals.all().order_by('-priority')
    target_scores = student.target_scores.all()

    # 2. 新增：获取学生成绩数据并按科目系列分组
    from score.models import ExamRecord, Exam, Subject
    exam_records = ExamRecord.objects.filter(student=student).select_related('exam', 'subject')

    # 组织成绩数据：按科目 -> 系列 -> 具体考试
    subject_scores_data = []

    # 定义科目映射
    subject_mapping = {
        'politics': {'name': '政治', 'icon': 'bi-flag', 'color': 'text-danger'},
        'english': {'name': student.english_type if student.english_type != '不考' else '英语', 'icon': 'bi-globe',
                    'color': 'text-primary'},
        'math': {'name': student.math_type if student.math_type != '不考' else '数学', 'icon': 'bi-calculator',
                 'color': 'text-success'},
        'professional_1': {'name': student.professional_subject_name or '专业课一', 'icon': 'bi-book',
                           'color': 'text-purple'},
        'professional_2': {'name': student.professional_subject_2_name or '专业课二', 'icon': 'bi-journal',
                           'color': 'text-warning'}
    }

    # 检查学生实际考试的科目
    active_subjects = []
    if student.has_politics:
        active_subjects.append('politics')
    if student.has_english:
        active_subjects.append('english')
    if student.has_math:
        active_subjects.append('math')
    if student.professional_subject_name:
        active_subjects.append('professional_1')
    if student.has_professional_2 and student.professional_subject_2_name:
        active_subjects.append('professional_2')

    # 为每个科目组织数据
    for subject_key in active_subjects:
        subject_info = subject_mapping[subject_key]

        # 获取该科目的所有成绩记录
        subject_records = exam_records.filter(
            subject__name__icontains=subject_info['name']
        ).order_by('-exam__exam_date')

        # 按考试系列分组
        series_data = {}
        for record in subject_records:
            # 从考试名称中提取系列名称
            series_name = extract_series_name(record.exam.name)

            if series_name not in series_data:
                series_data[series_name] = {
                    'name': series_name,
                    'records': [],
                    'count': 0,
                    'avg_score': 0
                }

            series_data[series_name]['records'].append({
                'id': record.id,
                'exam_name': record.exam.name,
                'score': record.score,
                'exam_date': record.exam.exam_date,
                'duration': record.exam_duration
            })
            series_data[series_name]['count'] += 1

        # 计算每个系列的平均分
        for series in series_data.values():
            if series['records']:
                total_score = sum(record['score'] for record in series['records'])
                series['avg_score'] = round(total_score / len(series['records']), 1)

        # 添加到科目数据
        subject_scores_data.append({
            'key': subject_key,
            'name': subject_info['name'],
            'icon': subject_info['icon'],
            'color': subject_info['color'],
            'series': list(series_data.values()),
            'total_records': len(subject_records)
        })

    # 3. 计算目标成绩统计（原有逻辑）
    target_stats = {
        'subject_count': target_scores.count(),
        'avg_confidence': 0,
        'high_risk_count': 0,
        'total_target_score': 0,
    }

    if target_scores.exists():
        total_confidence = sum(target.confidence_level for target in target_scores)
        target_stats['avg_confidence'] = round(total_confidence / target_scores.count())
        target_stats['high_risk_count'] = sum(1 for target in target_scores if target.risk_level == 'high')
        target_stats['total_target_score'] = sum(target.realistic_target for target in target_scores)

    # 4. 预处理学习目标：计算进度百分比（保持原有逻辑）
    for goal in study_goals:
        progress_percent = 0
        if goal.target_score and goal.current_level and goal.target_score > 0:
            progress_percent = round((goal.current_level / goal.target_score) * 100, 2)
        setattr(goal, 'progress_percent', progress_percent)

    # 5. 预处理往年成绩：计算统计数据（保持原有逻辑）
    score_stats = {
        'max_score': 0,
        'avg_score': 0.0,
        'latest_score': 0,
        'trend': '数据不足',
        'trend_icon': 'bi-question-circle',
        'trend_color': 'text-gray-500'
    }

    if past_scores.exists():
        score_stats['max_score'] = past_scores.aggregate(Max('total_score'))['total_score__max'] or 0
        score_stats['avg_score'] = round(past_scores.aggregate(Avg('total_score'))['total_score__avg'] or 0, 1)
        score_stats['latest_score'] = past_scores.first().total_score

        if past_scores.count() >= 2:
            latest = past_scores.first()
            prev = past_scores[1]
            if latest.total_score > prev.total_score:
                score_stats['trend'] = f'上升{latest.total_score - prev.total_score}分'
                score_stats['trend_icon'] = 'bi-arrow-trend-up'
                score_stats['trend_color'] = 'text-green-500'
            elif latest.total_score < prev.total_score:
                score_stats['trend'] = f'下降{prev.total_score - latest.total_score}分'
                score_stats['trend_icon'] = 'bi-arrow-trend-down'
                score_stats['trend_color'] = 'text-red-500'
            else:
                score_stats['trend'] = '持平'
                score_stats['trend_icon'] = 'bi-arrow-right'
                score_stats['trend_color'] = 'text-gray-500'

    # 6. 预处理系统信息：计算相对时间（保持原有逻辑）
    def get_time_description(dt):
        delta = timezone.now() - dt
        if delta.days <= 1:
            return '今天'
        elif delta.days <= 30:
            return f'{delta.days}天前'
        elif delta.days <= 365:
            return f'{delta.days // 30}月前'
        else:
            return f'{delta.days // 365}年前'

    create_time_desc = get_time_description(student.created_at)

    update_delta = timezone.now() - student.last_updated
    if update_delta.days <= 1:
        update_time_desc = '刚刚更新'
        update_time_color = 'text-green-500'
    elif update_delta.days <= 7:
        update_time_desc = f'{update_delta.days}天前'
        update_time_color = 'text-blue-500'
    else:
        update_time_desc = f'{update_delta.days}天前'
        update_time_color = 'text-muted'

    return render(request, 'users/student_detail.html', {
        'student': student,
        'past_scores': past_scores,
        'study_goals': study_goals,
        'target_scores': target_scores,
        'target_stats': target_stats,
        'score_stats': score_stats,
        'subject_scores_data': subject_scores_data,  # 新增：科目成绩数据
        'create_time_desc': create_time_desc,
        'update_time_desc': update_time_desc,
        'update_time_color': update_time_color
    })


def extract_series_name(exam_name):
    """
    从考试名称中提取系列名称
    例如："张宇第一套" -> "张宇", "李林第三套" -> "李林"
    """
    import re

    # 常见分隔符：空格、括号、数字等
    patterns = [
        r'^([^\d\s\(\)]+)',  # 匹配开头非数字非空格非括号的字符
        r'^([\u4e00-\u9fa5]+)',  # 匹配中文字符
        r'^([A-Za-z]+)',  # 匹配英文字母
    ]

    for pattern in patterns:
        match = re.match(pattern, exam_name.strip())
        if match:
            return match.group(1).strip()

    # 如果无法提取，返回原名称的前4个字符
    return exam_name[:4] + ('...' if len(exam_name) > 4 else '')


@login_required()
def student_update(request, pk):
    """更新学生视图"""
    student = get_object_or_404(Student, pk=pk)

    if request.method == 'POST':
        # 【修复】添加 request 参数
        form = StudentForm(request.POST, instance=student, request=request)
        if form.is_valid():
            try:
                student = form.save(commit=True)
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': True,
                        'message': '学生信息更新成功！',
                        'redirect_url': f'/users/{student.id}/detail/'  # 【修复】重定向到详情页
                    })
                messages.success(request, '学生信息更新成功！')
                return redirect('users:student_detail', pk=student.id)  # 【修复】重定向到详情页
            except Exception as e:
                # 添加异常处理，与 student_create 保持一致
                error_msg = f'更新失败：{str(e)}'
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return render(request, 'users/student_form.html', {
                    'form': form,
                    'title': '编辑学生信息',
                    'student': student
                })
        else:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': False,
                    'errors': form.errors
                })
            return render(request, 'users/student_form.html', {
                'form': form,
                'title': '编辑学生信息',
                'student': student
            })
    else:
        # GET请求：初始化表单时也要传递 request 参数
        form = StudentForm(instance=student, request=request)

    return render(request, 'users/student_form.html', {
        'form': form,
        'title': '编辑学生信息',
        'student': student
    })


@login_required()
def student_delete(request, pk):
    """删除学生视图"""
    student = get_object_or_404(Student, pk=pk)

    if request.method == 'POST':
        student_name = student.name
        username = student.user.username  # 获取用户名用于消息显示

        # 先获取关联的User对象
        user = student.user

        # 删除Student（由于on_delete=CASCADE，应该会自动删除User）
        student.delete()

        # 但为了确保User被删除，我们可以显式检查并删除
        # 如果User还存在（可能由于某些原因级联删除失败），则手动删除
        if User.objects.filter(id=user.id).exists():
            user.delete()

        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': f'学生"{student_name}"(账号:{username})已成功删除！'
            })
        messages.success(request, f'学生"{student_name}"(账号:{username})已成功删除！')
        return redirect('users:student_list')

    return render(request, 'users/student_confirm_delete.html', {'student': student})

@login_required()
def student_search(request):
    """学生搜索功能（补充分页逻辑）"""
    query = request.GET.get('q', '').strip()  # 搜索关键词
    page_num = request.GET.get('page', 1)     # 当前页码（默认第1页）

    # 1. 执行搜索查询
    if query:
        students = Student.objects.filter(
            Q(name__icontains=query) |
            Q(undergraduate_school__icontains=query) |
            Q(target_school__icontains=query) |
            Q(target_major__icontains=query)
        ).order_by('-created_at')  # 保持与列表页一致：按创建时间倒序
    else:
        # 若未输入关键词，默认返回所有学生（与列表页逻辑对齐）
        students = Student.objects.all().order_by('-created_at')

    # 2. 添加分页处理（与 StudentListView 的 paginate_by=10 保持一致）
    paginator = Paginator(students, 10)  # 每页显示10条
    page_obj = paginator.get_page(page_num)  # 获取当前页数据（自动处理越界页码）

    # 3. 传递分页相关变量到模板（与 StudentListView 传递的变量名一致，确保模板兼容性）
    return render(request, 'users/student_list.html', {
        'students': page_obj,          # 模板循环时用 page_obj（而非原始列表）
        'page_obj': page_obj,          # 分页控件需要的核心对象（页码、上下页等）
        'is_paginated': page_obj.has_other_pages(),  # 判断是否需要显示分页控件
        'search_query': query,         # 保留搜索关键词（分页时不丢失）
        'page_title': f'搜索结果：{query}',  # 页面标题（显示搜索关键词，优化体验）
        'add_student_url': 'users:student_create'  # 保持与列表页一致：传递添加学生URL
    })


@login_required()
def past_score_create(request, student_id):
    """添加往年成绩"""
    student = get_object_or_404(Student, pk=student_id)

    # 只有二战及以上考生才能添加往年成绩
    if student.attempt_count == '一战':
        messages.error(request, '一战考生无需填写往年成绩')
        return redirect('users:student_detail', pk=student_id)

    if request.method == 'POST':
        form = PastExamScoreForm(request.POST, student=student)  # 【修改】传递 student 参数
        if form.is_valid():
            past_score = form.save(commit=False)
            past_score.student = student
            past_score.save()

            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': True,
                    'message': '往年成绩添加成功！'
                })
            messages.success(request, '往年成绩添加成功！')
            return redirect('users:student_detail', pk=student_id)
    else:
        form = PastExamScoreForm(student=student)  # 【修改】传递 student 参数

    return render(request, 'users/past_score_form.html', {
        'form': form,
        'student': student,
        'title': '添加往年成绩'
    })


@login_required()
def past_score_update(request, student_id, score_id):
    """编辑往年成绩"""
    student = get_object_or_404(Student, pk=student_id)
    past_score = get_object_or_404(PastExamScore, pk=score_id, student=student)

    if request.method == 'POST':
        form = PastExamScoreForm(request.POST, instance=past_score, student=student)  # 【修改】传递 student 参数
        if form.is_valid():
            try:
                form.save()

                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': True,
                        'message': '往年成绩更新成功！',
                        'redirect_url': f'/users/{student.id}/detail/'
                    })
                messages.success(request, '往年成绩更新成功！')
                return redirect('users:student_detail', pk=student.id)

            except Exception as e:
                error_msg = f'更新失败：{str(e)}'
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return render(request, 'users/past_score_form.html', {
                    'form': form,
                    'title': '编辑往年成绩',
                    'student': student,
                    'past_score': past_score
                })
        else:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': False,
                    'errors': form.errors
                })
            return render(request, 'users/past_score_form.html', {
                'form': form,
                'title': '编辑往年成绩',
                'student': student,
                'past_score': past_score
            })
    else:
        form = PastExamScoreForm(instance=past_score, student=student)  # 【修改】传递 student 参数

    return render(request, 'users/past_score_form.html', {
        'form': form,
        'title': '编辑往年成绩',
        'student': student,
        'past_score': past_score
    })


@login_required()
def past_score_delete(request, student_id, score_id):
    """删除往年成绩"""
    student = get_object_or_404(Student, pk=student_id)
    past_score = get_object_or_404(PastExamScore, pk=score_id, student=student)

    if request.method == 'POST':
        exam_year = past_score.exam_year
        past_score.delete()

        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': f'{exam_year}年成绩已成功删除！'
            })

        messages.success(request, f'{exam_year}年成绩已成功删除！')
        return redirect('users:student_detail', pk=student_id)

    # 如果不是POST请求，返回错误
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({
            'success': False,
            'message': '无效的请求方法'
        }, status=400)

    messages.error(request, '无效的请求方法')
    return redirect('users:student_detail', pk=student_id)

@login_required()
def study_goal_create(request, student_id):
    """添加学习目标"""
    student = get_object_or_404(Student, pk=student_id)

    if request.method == 'POST':
        form = StudyGoalForm(request.POST, student=student)
        if form.is_valid():
            study_goal = form.save(commit=False)
            study_goal.student = student
            study_goal.save()

            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': True,
                    'message': '学习目标添加成功！'
                })
            messages.success(request, '学习目标添加成功！')
            return redirect('users:student_detail', pk=student_id)
    else:
        form = StudyGoalForm(student=student)

    return render(request, 'users/study_goal_form.html', {
        'form': form,
        'student': student,
        'title': '添加学习目标'
    })


@login_required
def target_score_create(request, student_id):
    """创建目标成绩"""
    student = get_object_or_404(Student, pk=student_id)
    print(f"DEBUG: 开始为目标成绩创建，学生: {student.name}, ID: {student.id}")

    if request.method == 'POST':
        form = TargetScoreForm(request.POST, student=student)
        print(f"DEBUG: 收到POST请求，表单绑定: {form.is_bound}")

        if form.is_valid():
            print(f"DEBUG: 表单验证通过")
            try:
                target_score = form.save(commit=False)
                print(f"DEBUG: 创建TargetScore实例，student_id: {target_score.student_id}")
                print(f"DEBUG: 表单student: {form.student.name if form.student else 'None'}")
                print(f"DEBUG: 实例student: {target_score.student.name if target_score.student else 'None'}")

                # 再次确保student被设置
                if not target_score.student_id:
                    target_score.student = student
                    print(f"DEBUG: 重新设置student: {target_score.student.name}")

                # 验证科目有效性
                if not target_score.is_subject_valid():
                    raise ValidationError("选择的科目与学生考试科目配置不匹配")

                target_score.save()
                print(f"DEBUG: 目标成绩保存成功，ID: {target_score.id}")
                print(f"DEBUG: 保存后的student_id: {target_score.student_id}")

                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': True,
                        'message': '目标成绩创建成功！'
                    })
                messages.success(request, '目标成绩创建成功！')
                return redirect('users:student_detail', pk=student_id)

            except ValidationError as e:
                print(f"DEBUG: 验证错误: {str(e)}")
                error_msg = str(e)
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': False,
                        'errors': {'__all__': [error_msg]}
                    })
                messages.error(request, error_msg)

            except Exception as e:
                print(f"DEBUG: 保存异常: {str(e)}")
                import traceback
                traceback.print_exc()
                error_msg = f'保存失败：{str(e)}'
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': False,
                        'errors': {'__all__': [error_msg]}
                    })
                messages.error(request, error_msg)
        else:
            print(f"DEBUG: 表单验证失败: {form.errors}")
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': False,
                    'errors': form.errors
                })
    else:
        form = TargetScoreForm(student=student)

    return render(request, 'users/target_score_form.html', {
        'form': form,
        'student': student,
        'title': '创建目标成绩'
    })


@login_required
def target_score_update(request, student_id, target_id):
    """更新目标成绩"""
    student = get_object_or_404(Student, pk=student_id)
    target_score = get_object_or_404(TargetScore, pk=target_id, student=student)

    if request.method == 'POST':
        form = TargetScoreForm(request.POST, instance=target_score, student=student)
        if form.is_valid():
            try:
                form.save()

                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': True,
                        'message': '目标成绩更新成功！',
                        'redirect_url': f'/users/{student.id}/detail/'
                    })
                messages.success(request, '目标成绩更新成功！')
                return redirect('users:student_detail', pk=student.id)

            except Exception as e:
                error_msg = f'更新失败：{str(e)}'
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': {'__all__': [error_msg]}})
                messages.error(request, error_msg)
                return render(request, 'users/target_score_form.html', {
                    'form': form,
                    'title': '编辑目标成绩',
                    'student': student,
                    'target_score': target_score
                })
        else:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': False,
                    'errors': form.errors
                })
            return render(request, 'users/target_score_form.html', {
                'form': form,
                'title': '编辑目标成绩',
                'student': student,
                'target_score': target_score
            })
    else:
        form = TargetScoreForm(instance=target_score, student=student)

    return render(request, 'users/target_score_form.html', {
        'form': form,
        'title': '编辑目标成绩',
        'student': student,
        'target_score': target_score
    })


@login_required
def target_score_delete(request, student_id, target_id):
    """删除目标成绩"""
    student = get_object_or_404(Student, pk=student_id)
    target_score = get_object_or_404(TargetScore, pk=target_id, student=student)

    if request.method == 'POST':
        subject_name = target_score.display_name
        target_score.delete()

        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': f'{subject_name}目标成绩已成功删除！'
            })

        messages.success(request, f'{subject_name}目标成绩已成功删除！')
        return redirect('users:student_detail', pk=student_id)

    # 如果不是POST请求，返回错误
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({
            'success': False,
            'message': '无效的请求方法'
        }, status=400)

    messages.error(request, '无效的请求方法')
    return redirect('users:student_detail', pk=student_id)

